package com.example.demo.controller;

import com.example.demo.entity.Player;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.response.UserResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/login")
    public UserResponse login(String username, String password) {
        try {
            User user = userMapper.getUserInfo(username);
            if (user != null && password.equals(user.getPassword())) {
                Player player = userMapper.getPlayerInfo(username);
                return new UserResponse(player, "Success");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new UserResponse(null, "Error");
    }

    @GetMapping("/register")
    public UserResponse register(String username, String password) {
        try {
            User user = userMapper.getUserInfo(username);
            if (user == null) {
                userMapper.addUserInfo(username, password);

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
                Date date = new Date(System.currentTimeMillis());
                userMapper.addPlayerInfo(username, formatter.format(date));

                Player player = userMapper.getPlayerInfo(username);
                return new UserResponse(player, "Success");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new UserResponse(null, "Error");
    }

    @GetMapping("/finish")
    public UserResponse finish(String username, int layout_id) {
        try {
            User user = userMapper.getUserInfo(username);
            if (user != null) {
                Player player = userMapper.getPlayerInfo(username);
                userMapper.finishGame(username, layout_id, "unknown");
                userMapper.updatePlayerInfo(username, player.getGame_total_cnt() + 1, player.getGame_finish_total_cnt() + 1, 0.0f);
                player = userMapper.getPlayerInfo(username);
                return new UserResponse(player, "Success");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new UserResponse(null, "Error");
    }
}
